package com.st.controller;


import com.github.wxpay.sdk.WXPayUtil;
import com.st.config.MyConfig;
import com.st.config.WebSocketServer;
import com.st.config.WeixinConfig;
import com.st.entity.Order;
import com.st.entity.Result;
import com.st.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("weixin")
public class PayController {

    @Autowired
    private IOrderService iOrderService;


    @RequestMapping("/unifiedorder")
    public Result unifiedorder(String id){
        System.out.println(id);
        return iOrderService.pay(id) ;
    }


    @RequestMapping("/notify")
    public String  notify(HttpServletRequest request){

        System.out.println("微信支付系统成功回调");
        InputStream inStream;
        try{
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inStream.read(buffer)) != -1){
                outSteam.write(buffer,0,len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(),"utf-8");
            System.out.println(result);

            //对xml进行解析 map
            Map<String,String> map = WXPayUtil.xmlToMap(result);
            //验证签名
            boolean signatureValid = WXPayUtil.isSignatureValid(map,
                    new MyConfig().getKey());
            System.out.println("验证签名是否正确："+signatureValid);
            System.out.println(map.get("out_trade_no"));//订单号
            String id =  map.get("out_trade_no");
            String total_fee = map.get("total_fee");
            System.out.println(map.get("result_code"));
            if(signatureValid&&"SUCCESS".equals(map.get("result_code"))){
                //修改订单状态(支付状态、订单状态、支付时间、修改时间)
//                Order order = new Order();
//                order.setId(id);
//                order.setOrderTime(new Date());
//                order.setOrderStatu(2);
                iOrderService.status(id);
            }
            iOrderService.status(id);
            Map data = new HashMap();
            data.put("return_code","SUCCESS");
            data.put("return_msg","OK");
            //map转xml
            String returnXml = WXPayUtil.generateSignedXml(data, new MyConfig().getKey());
            //给客户端（浏览器）发消息,告诉客户端已经支付成功
            WebSocketServer.sendMessageToClient(id,"success");
            return returnXml;
        }catch(Exception e){
            e.printStackTrace();
            return "";
        }
    }


    //查询订单状态的接口
    @RequestMapping("/queryOrder")
    public  Result queryOrder(String id){
        return iOrderService.queryOrderStatus(id);
    }

    @RequestMapping("findOrder")
    public Order findOrder(String id){
        Order orderById = iOrderService.findOrderById(id);
        return orderById;
    }


    //支付成功查询信息
    @RequestMapping("/getInfo")
    public Result getInfo(String id){
       return iOrderService.getInfo(id);
    }

}